package com.example.finalassignment.controller;

import com.example.finalassignment.common.ThreadContext;
import com.example.finalassignment.exception.ServiceException;
import com.example.finalassignment.mapper.StarsMapper;
import com.example.finalassignment.mapper.TechnologyInfoMapper;
import com.example.finalassignment.pojo.Stars;
import com.example.finalassignment.pojo.response.ResultResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/stars")
public class StarsController {

    private final StarsMapper starsMapper;
    private final TechnologyInfoMapper technologyInfoMapper;

    public StarsController(StarsMapper starsMapper, TechnologyInfoMapper technologyInfoMapper) {
        this.starsMapper = starsMapper;
        this.technologyInfoMapper = technologyInfoMapper;
    }

    /**
     * 点赞
     * @return
     */
    @GetMapping("/like/{uuid}")
    public ResultResponse getStarsByLike(@PathVariable("uuid") String uuid) {
        String id = ThreadContext.getUserId();

        try {
            Stars oldStars = starsMapper.selectByPrimaryKey(uuid);
            if(oldStars == null){
                Stars newStars = new Stars();
                newStars.setUuid(uuid);
                newStars.setId(0);
                newStars.setUserId(id);
                newStars.setCreateTime(new Date());
                technologyInfoMapper.updateDraftsByUUIDToStarsAdd(uuid);
                starsMapper.insertSelective(newStars);
                return ResultResponse.success("点赞成功");
            }else {
                starsMapper.closeByUuidAndUserId(uuid,id);
                technologyInfoMapper.updateDraftsByUUIDToStarsCut(uuid);
                return ResultResponse.success("取消点赞");
            }
        }catch (Exception e){
            throw new ServiceException(201);
        }

    }

    /**
     * 查看当前用户有没有对当前文章点赞
     */
    @GetMapping("/{uuid}")
    public ResultResponse getStarsByUuid(@PathVariable("uuid") String uuid) {
        String id = ThreadContext.getUserId();
        try {
            Stars starsByUserId = starsMapper.getStarsByUserId(uuid, id);
            if(starsByUserId == null){
                return ResultResponse.success("否");
            }
            return ResultResponse.success("是");
        }catch (Exception e){
            throw new ServiceException(201);
        }
    }
}
